import 'package:bpb/common/CommonData.dart';
import 'package:bpb/db/db_helper.dart';
import 'package:bpb/framework/base/base_controller.dart';
import 'package:bpb/framework/utils/date_utils.dart';
import 'package:bpb/util/date_tool.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

class HistoryController extends BaseController {
  static const String dataTypeWeek = "Week";
  static const String dataTypeMonth = "Month";
  static const String dataTypeQuarter = "Quarter";
  static const String dataTypeYear = "Year";

  var tabs =
      [
        {"name": dataTypeWeek, "checked": true, "value": 1},
        {"name": dataTypeMonth, "checked": false, "value": 2},
        {"name": dataTypeQuarter, "checked": false, "value": 3},
        {"name": dataTypeYear, "checked": false, "value": 4},
      ].obs;

  var datas = <Map<String, Object?>?>[].obs;

  //图表
  var lengends =
      [
        {"title": "SYS", "icon": "images/icon_chart_lengend_sys.png", "checked": true},
        {"title": "DIA", "icon": "images/icon_chart_lengend_dia.png", "checked": true},
        {"title": "Pulse", "icon": "images/icon_chart_lengend_pulse.png", "checked": true},
      ].obs;

  var dateTitleFromToEnd = "".obs;

  var currentWeekIndex = 0;
  var currentMonthIndex = 0;
  var currentQuarterIndex = 0;
  var currentYearIndex = 0;

  DateFormat ymd = DateFormat("yyyy-MM-dd");

  var visibleSwitchTime = true.obs;

  var rangeDatas =
      [
        {"title": "SYS Range", "margin": 0.0, "unit": "mmhg","min":250,"max":0},
        {"title": "DIA Range", "margin": 10.0, "unit": "mmhg","min":250,"max":0},
        {"title": "Pulse Range", "margin": 0.0, "unit": "bpm","min":250,"max":0},
      ].obs; //血压的3个平均指标

  var avgData = {"avgSys": 0, "avgDia": 0, "avgPulse": 0,"avgLevel":"","bgColor":Colors.red,"textColor":Colors.black}.obs;

  @override
  void onInit() {
    super.onInit();
    onTabChecked();
  }

  ///tab选中按需查询
  Future<void> onTabChecked() async {
    List<DateTime> dates = [];
    List<Map<String, DateTime>> datesQuatores = [];

    String dataType = capitalizeProper(getDatType());
    DateTime? start;
    DateTime? end;

    switch (dataType) {
      case dataTypeWeek:
        {
          dates = DateTool.getWeekDates(weeksAgo: currentWeekIndex);
          start = dates[0];
          end = dates[dates.length - 1];
          debugPrint("start :${start} -- ${end}");
          visibleSwitchTime.value = true;
        }
        break;
      case dataTypeMonth:
        {
          dates = DateTool.getMonthDates(offset: currentMonthIndex);
          start = dates[0];
          end = dates[dates.length - 1];
          debugPrint("start :${start} -- ${end}");
          visibleSwitchTime.value = true;
        }
        break;
      case dataTypeQuarter:
        {
          datesQuatores = DateTool.getQuarterWeeks(DateTime.now(), offset: currentQuarterIndex);
          start = datesQuatores[0]["start"];
          end = datesQuatores[datesQuatores.length - 1]["end"];
          visibleSwitchTime.value = true;
        }
        break;
      case dataTypeYear:
        {
          dates = DateTool.getYearDates(yearsAgo: currentYearIndex);
          start = dates[0];
          end = dates[dates.length - 1];
          debugPrint("start :${start} -- ${end}");
          visibleSwitchTime.value = false;
        }
        break;
    }

    ///=========================================================================================================

    for (var e in tabs) {
      if (e["checked"] == true) {
        switch (e["value"]) {
          case 1:
            {
              var ret = await DBHelper.getDailyAverages(start!, end!);
              bindDataTypeForDataList(getDatType(), ret);
              datas.value = ret;
            }
            break;
          case 2:
            {
              var ret = await DBHelper.getDailyAverages(start!, end!);
              bindDataTypeForDataList(getDatType(), ret);
              datas.value = ret;
            }
            break;
          case 3:
            {
              var ret = await DBHelper.getWeeklyAverages(start!, end!);
              // var ret = (await DBHelper.get12WeeksAverage(offset: currentQuarterIndex)).toList();
              bindDataTypeForDataList(getDatType(), ret);
              datas.value = ret;
            }
            break;
          case 4:
            {
              var ret = await DBHelper.getLastYearMonthlyStats();
              bindDataTypeForDataList(getDatType(), ret);
              datas.value = ret;
            }
            break;
        }
        break;
      }
    }

    debugPrint("数据条数:${datas.value.length}");
    for (var e in datas.value) {
      debugPrint("${e.toString()}");
    }


    dateTitleFromToEnd.value = "${DateUtil.DD_MM_YYYY.format(start!)} - ${DateUtil.DD_MM_YYYY.format(end!)}";
    if (getDatType() == dataTypeYear.toLowerCase()) {
      dateTitleFromToEnd.value = "The last year";
    }
  }

  bindDataTypeForDataList(String type, List<dynamic> dataList) {

    int minSys = 250;
    int maxSys =0 ;

    int minDia = 250;
    int maxDia = 0;

    int minPulse = 250;
    int maxPulse = 0;

    int itemCount=0;

    int totalSys=0;
    int totalDia=0;
    int totalPulse=0;

    for (var e in dataList) {

      int sys = double.parse(e["sys"].toString()).toInt();
      int dia = double.parse(e["dia"].toString()).toInt();
      int pulse = double.parse(e["pulse"].toString()).toInt();

      if(sys==0 || dia==0 || pulse==0){
        continue;
      }

      itemCount++;

      totalSys+=sys;
      totalDia+=dia;
      totalPulse+=pulse;


      if(sys<minSys){
        minSys=sys;
      }

      if(sys>maxSys){
        maxSys=sys;
      }

      if(dia<minDia){
        minDia=dia;
      }

      if(dia>maxDia){
        maxDia=dia;
      }


      if(pulse<minPulse){
        minPulse=pulse;
      }

      if(pulse>maxPulse){
        maxPulse=pulse;
      }
    }


    if(itemCount!=0){

      int avgSys=(totalSys/itemCount).toInt();
      int avgDia=(totalDia/itemCount).toInt();
      int avgPulse=(totalPulse/itemCount).toInt();

      avgData.value["avgSys"]=avgSys;
      avgData.value["avgDia"]=avgDia;
      avgData.value["avgPulse"]=avgPulse;

      String avgLevel=CommonData.getBloodPressureLevel(avgSys, avgDia)[0];
      avgData.value["avgLevel"]=avgLevel;

      var colors=CommonData.getColorByLevel(avgLevel);
      avgData.value["bgColor"]=colors[0];
      avgData.value["textColor"]=colors[1];


      ///====================================================================================


      avgData.value=Map.of(avgData.value);

      rangeDatas.value[0]["min"]=minSys;
      rangeDatas.value[0]["max"]=maxSys;

      rangeDatas.value[1]["min"]=minDia;
      rangeDatas.value[1]["max"]=maxDia;


      rangeDatas.value[2]["min"]=minPulse;
      rangeDatas.value[2]["max"]=maxPulse;

      rangeDatas.value=List.of(rangeDatas.value);

    }else{

      avgData.value["avgSys"]=0;
      avgData.value["avgDia"]=0;
      avgData.value["avgPulse"]=0;

      avgData.value=Map.of(avgData.value);

      rangeDatas.value[0]["min"]=0;
      rangeDatas.value[0]["max"]=0;

      rangeDatas.value[1]["min"]=0;
      rangeDatas.value[1]["max"]=0;


      rangeDatas.value[2]["min"]=0;
      rangeDatas.value[2]["max"]=0;

      rangeDatas.value=List.of(rangeDatas.value);

    }


    // if(dataList.isNotEmpty){
    //   for (var e in dataList) {
    //     e["dataType"]=type;
    //   }
    // }
  }

  String getDatType() {
    String dataType = "";
    for (var ex in tabs.value) {
      if (ex["checked"] == true) {
        dataType = ex["name"].toString().toLowerCase();
        break;
      }
    }
    return dataType;
  }

  String capitalizeProper(String input) {
    if (input.isEmpty) return input;
    return input[0].toUpperCase() + input.substring(1).toLowerCase();
  }

  void onPreClick() {
    String dataType = capitalizeProper(getDatType());
    switch (dataType) {
      case dataTypeWeek:
        {
          currentWeekIndex--;
        }
        break;
      case dataTypeMonth:
        {
          currentMonthIndex--;
        }
        break;
      case dataTypeQuarter:
        {
          currentQuarterIndex--;
        }
        break;
      case dataTypeYear:
        {
          currentYearIndex--;
        }
        break;
    }
    onTabChecked();
  }

  void onNextClick() {
    String dataType = capitalizeProper(getDatType());
    switch (dataType) {
      case dataTypeWeek:
        {
          currentWeekIndex++;
        }
        break;
      case dataTypeMonth:
        {
          currentMonthIndex++;
        }
        break;
      case dataTypeQuarter:
        {
          currentQuarterIndex++;
        }
        break;
      case dataTypeYear:
        {
          currentYearIndex++;
        }
        break;
    }
    onTabChecked();
  }
}
